
class BabakanInfo extends AbstractPlugin {

  static BASE_URL = 'https://www.88mv.org';

  async fetchWebsiteInfo() {
    const url = window.location.href;

    const parser = new DOMParser();
    const doc = parser.parseFromString(document.body.outerHTML, 'text/html');

    const playSources = [];

    let tabLists = doc.querySelectorAll('.playlist');
    if(!tabLists || tabLists.length === 0) {
      tabLists = doc.querySelectorAll('.tab2 .ulNumList');
    }
    let tabTitles = doc.querySelectorAll('.playfrom.tab8 ul li');
    if(!tabTitles || tabTitles.length === 0) {
      tabTitles = doc.querySelectorAll('.tab2 .tabt3 span');
    }

    tabLists.forEach((tabList, index) => {
      const items = tabList.querySelectorAll('li a');
      if (items.length > 0) {
        const episodes = [];
        items.forEach((item) => {
          const episodeItem = new Episode();
          episodeItem.title = item.textContent.trim();
          const href = item.getAttribute('href');
          episodeItem.link = href.startsWith('/') ? `${BabakanInfo.BASE_URL}${href}` : href;
          episodes.push(episodeItem);
        })
        const title = index < tabTitles.length ? tabTitles[index].textContent.trim() : '';
        playSources.push(new Source({
          title: title,
          episodes: episodes
        }));
      }
    });

    const websiteInfo = new WebsiteInfo();
    websiteInfo.type = 'video';
    let titleElement = doc.querySelector('.ct-c h1');
    if(titleElement) {
      websiteInfo.title = titleElement.textContent.trim();
    } else {
      const titleMatch = document.body.outerHTML.match(/mac_name\s*=\s*'([^']+)'/);
      if(titleMatch) {
        websiteInfo.title = titleMatch[1];
      }
    }
    websiteInfo.link = url;
    websiteInfo.sources = playSources;

    const playRegex = /\/vod-play-id-/;
    if(playRegex.test(url)) {
      const [src, ep] = this.getSourceAndEpisode(url);
      websiteInfo.playUrl = await this.getPlayUrlFromBody(document.body.outerHTML, src, ep);
      let contain = doc.querySelector('.playlist');
      if(!contain) {
        contain = doc.querySelector('.tab2');
      }
      if(contain) {
        const curEp = contain.querySelector('.selected a');
        if(curEp) {
          const href = curEp.getAttribute('href');
          const curEpLink = href.startsWith('/') ? `${BabakanInfo.BASE_URL}${href}` : href;
          [websiteInfo.sourceIndex, websiteInfo.episodeIndex] = AbstractPlugin.findEpisode(playSources, curEpLink);
        }
      }
    }
    return websiteInfo;
  }

  async fetchPlayUrlInfo(url) {
    const [src, ep] = this.getSourceAndEpisode(url);
    const http_headers = {
      'User-Agent': BabakanInfo.DEFAULT_USER_AGENT,
      'Origin': BabakanInfo.BASE_URL,
    };
    const result = await doHttpRequestSync(url, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    return this.getPlayUrlFromBody(result.body, src, ep)
  }

  async getPlayUrlFromBody(body, src, ep) {
    const [from, srcUrl] = this.getSrcUrl(body, src, ep);
    if(!srcUrl) return null;

    let finalUrl = srcUrl;
    const urlScheme = srcUrl.slice(0, 4);
    if(from === 'kuyun') {
      finalUrl = await this.getPlayableUrlKuyun(srcUrl);
    } else if (urlScheme !== 'http') {
      finalUrl = await this.getM3u8Url(srcUrl);
    }

    const playUrl = new PlayUrlInfo();
    playUrl.type = 'video';
    playUrl.urls = [finalUrl];
    return playUrl;
  }

  getSrcUrl(body, src, ep) {
    const macFromMatch = body.match(/mac_from='([^']+)'/);
    if(!macFromMatch) return [null, null];

    const macFroms = macFromMatch[1].split('$$$');
    const from = macFroms[src - 1];

    const macUrlsMatch = body.match(/mac_url=unescape\('([^']+)'\)/);
    if(!macUrlsMatch) return [null, null];

    function hexToChar(x) {
      return String.fromCharCode(parseInt(x, 16));
    }

    function urldecode(url) {
      return url.replace(/%([0-9A-Fa-f]{2})/g, (match, p1) => hexToChar(p1));
    }

    const macUrls = urldecode(macUrlsMatch[1]).split('$$$');
    const urls = macUrls[src - 1].split('#');
    const urlMatch = urls[ep - 1].match(/\$([^$]+)/);

    return urlMatch ? [from, urlMatch[1]] : [null, null];
  }

  getSourceAndEpisode(url) {
    const match = url.match(/src-(\d+)-num-(\d+)/);
    return match ? [parseInt(match[1]), parseInt(match[2])] : [-1, -1];
  }

  async getM3u8Url(url) {
    const http_headers = {
      'User-Agent': BabakanInfo.DEFAULT_USER_AGENT,
      // 'Origin': BabakanInfo.BASE_URL,
    };
    const parseUrl = `https://zj.jsjinfu.com:8443/?url=${url}`;
    const result = await doHttpRequestSync(parseUrl, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    const match = result.body.match(/video_url = '([^']+)'/);
    return match ? match[1] : null;
  }

  async getPlayableUrlKuyun(url) {
    const http_headers = {
      'User-Agent': BabakanInfo.DEFAULT_USER_AGENT,
      // 'Origin': BabakanInfo.BASE_URL,
    };
    const result = await doHttpRequestSync(url, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }

    const match = result.body.match(/main\s*=\s*"([^"]+)"/);
    if(match) {
      let srcUrl = match[1];
      if(srcUrl.includes('m3u8')) {
        const isHttp = srcUrl.startsWith('http');
        const baseUrl = new URL(url);
        if(!isHttp) {
          if(srcUrl.startsWith('/')) {
            srcUrl = `${baseUrl.origin}${srcUrl}`;
          } else {
            const lastSlashIndex = baseUrl.href.lastIndexOf('/');
            srcUrl = baseUrl.href.slice(0, lastSlashIndex + 1) + srcUrl;
          }
        }
        return srcUrl;
      }
    }
    return null;
  }

}
// Registry.registerClass("BabakanInfo", new BabakanInfo());